package com.dropesoft.ui;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.os.Bundle;
import android.text.format.Time;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.dropesoft.biz.TrainingDbAdapter;
import com.dropesoft.biz.Utility;

import dropesoft.com.R;

public class ListaAllenamenti extends ListActivity {

	private int _currentId =0;
	private TrainingDbAdapter _ga = null;
	private String _currentMonth = null;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		 _ga = new TrainingDbAdapter(this);
		 _ga.open();
		 
		
		ListView lv = getListView();
		
		
		 
        View header = getLayoutInflater().inflate(R.layout.training_list_header, null);
        
        // Setting dell' header
             
        TextView tvPeriod = (TextView) header.findViewById(R.id.textViewPeriod);
        Date now = new Date();
        tvPeriod.setText(new SimpleDateFormat("MMMM - yyyy ").format(now).toUpperCase());
        ImageButton ivadd =  (ImageButton) header.findViewById(R.id.ivAdd);
        
        _currentMonth = new SimpleDateFormat("MM").format(now);
        
        lv.addHeaderView(header, null, false);
		
		lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
		    //@Override
		    public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) 
		    {
		        return onLongListItemClick(v,pos,id);
		    }
		});
		lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
		    //@Override
		    public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
		    	visualizzaDettaglio(v, pos, id);
		    }
		});
		ivadd.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				nuovoAllenamento();
			}
		});
		
		
	}
	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		_ga.close();
	}
	
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		
		super.onResume();
		listaAllenamenti();
	}
 

	private void listaAllenamenti()
	{
		Cursor cursor = null;
		try
		{
			cursor = _ga.listMonthTraining(_currentMonth);
			startManagingCursor(cursor);
		}
		catch(SQLException ex)
		{}
		// Adapter per la lista
		setListAdapter(new ListaAllenamentiCursor(this,R.layout.lista_allenamenti, cursor, new String[]{}, new int[]{}));
	}

	private void visualizzaDettaglio(View v, int pos, long id)
	{
		Intent intent = new Intent(this, DettaglioAllenamento.class);
		intent.putExtra("ida", id);
    	startActivity(intent);	
	}
	private void modificaDettaglio()
	{
		Intent intent = new Intent(this, GestisciAllenamento.class);
		intent.putExtra("opModifica", true);
		intent.putExtra("idAllenamento", _currentId);
    	startActivity(intent);	
	}
	private void nuovoAllenamento()
	{
		Intent intent = new Intent(this, GestisciAllenamento.class);
    	intent.putExtra("opModifica", false);
    	startActivity(intent);	
	}
	 private void richiestaEliminaAllenamento()
	 {
		 AlertDialog.Builder builder = new AlertDialog.Builder(this);
		 builder.setMessage(R.string.allenamento_msg_elimina)
		        .setCancelable(false)
		        .setPositiveButton(R.string.msg_yes, new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int id) {
		            	eiliminaAllenamento();
		            	listaAllenamenti();
		            	
		            }
		        })
		        .setNegativeButton(R.string.msg_no, new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int id) {
		                 dialog.cancel();
		            }
		        });
		 AlertDialog alert = builder.create();
		 alert.show();
	 }
	 private void eiliminaAllenamento()
	 {
		 try		
		 {
    		 _ga.deleteTraining(_currentId);
		 }
		 catch(Exception e) 
		 {
			 			 
		 }
	 }
	protected boolean onLongListItemClick(View v, int pos, long id) 
	{
		final CharSequence[] items = { getResources().getString(R.string.btnModifica), getResources().getString(R.string.btnElimina) };
		_currentId = (int)id;
	    AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    builder.setTitle(R.string.msg_opzione);
	    builder.setItems(items, new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int item) {
	        	if (item == 0)
	        		modificaDettaglio();
	        	else if(item == 1)
	        		richiestaEliminaAllenamento(); //Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
	        }
	    });
	    AlertDialog alert = builder.create();
	    alert.show();
	    return true;
	}


	/*
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) 
	{
		//String item = (String) getListAdapter().getItem(position);
		//Toast.makeText(this,  id+"", Toast.LENGTH_LONG).show();
		Intent intent = new Intent(this, DettaglioAllenamento.class);
		intent.putExtra("ida", id);
    	startActivity(intent);	
    }
		*/
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu_allenamento, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
       
        case R.id.menuNuovoAllenamento:
        	
        	Intent intent = new Intent(this, GestisciAllenamento.class);
        	intent.putExtra("opModifica", false);
        	startActivity(intent);	
        	break;
 
    }
    return true;
    
	
    
}
	
	private final class ListaAllenamentiCursor extends SimpleCursorAdapter
	{
		private Cursor _c;
        public ListaAllenamentiCursor(Context context, int layout, Cursor c,
				String[] from, int[] to) {
			super(context, layout, c, from, to);
			this._c = c;
			 
			// TODO Auto-generated constructor stub
		}
		
		 @Override
		    public void bindView(View view, Context context, Cursor cursor) {
		        super.bindView(view, context, cursor);
		        
		    }
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if (convertView == null)
			{
				convertView = getLayoutInflater().inflate(
					R.layout.lista_allenamenti, null);
			}
			_c.moveToPosition(position);
			
			TextView tvData = (TextView) convertView.findViewById(R.id.data);
			TextView tvDati = (TextView) convertView.findViewById(R.id.dati);
			//ImageView ivEsito = (ImageView) convertView.findViewById(R.id.esitotr);
			TextView tvTipo = (TextView) convertView.findViewById(R.id.tipo);
			TextView tvEsitoColor = (TextView) convertView.findViewById(R.id.esitoColor);
			TextView tvNote = (TextView) convertView.findViewById(R.id.note);
			
			tvNote.setVisibility(View.INVISIBLE);
			
			if(_c.getString(4) != null && !_c.getString(4).trim().equals("") )
				tvNote.setVisibility(View.VISIBLE);
			
			switch(_c.getInt(13))	
			{
				case 0:
					tvTipo.setBackgroundColor(getResources().getColor(R.color.color_nuoto));
					tvTipo.setText(R.string.allenamento_abb_nuoto);
				break;
				case 1:
					tvTipo.setBackgroundColor(getResources().getColor(R.color.color_bici));
					tvTipo.setText(R.string.allenamento_abb_bici);
				break;
				case 2:
					tvTipo.setBackgroundColor(getResources().getColor(R.color.color_corsa));
					tvTipo.setText(R.string.allenamento_abb_corsa);
				break;
			}
			
			
			
			Date data = null;
			try {
				data = Utility.IsoFormat.parse(_c.getString(2));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			tvData.setText(Utility.SimpleFormat.format(data));
			String sottoTitolo = "";
			float tempo =  _c.getFloat(5);
			int ore =  (int)tempo / 3600;
			int minuti = (int)((tempo % 3600)/60);
			int secondi = (int)((tempo % 3600)%60);
			
			
			if (!_c.isNull(5)) sottoTitolo += ore +"h " + minuti + "m " + secondi +"s ";
			if (!_c.isNull(6)) sottoTitolo += " " + _c.getFloat(6) + " km ";
			convertView.setId(_c.getInt(0));
			tvDati.setText(sottoTitolo);
			
			
			if (_c.getInt(12)==1)	tvEsitoColor.setBackgroundColor(getResources().getColor(R.color.color_esito_ok));
			else tvEsitoColor.setBackgroundColor(getResources().getColor(R.color.color_esito_ko));
			
			return convertView;
		}
	}
	
	
	
}
